import { login, getInfo, menu } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRoutes } from '@/router'
import store from '@/store'
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  user: {},
  quanxian: []
}
const getters = {
  avatar: state => state.avatar
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_QUANXIAN(state, quanxian) {
    state.quanxian = quanxian
  }
}

const actions = {
  // 登入
  login({ commit }, {userInfo,VUE_APP_VERSION}) {
    return new Promise((resolve, reject) => {
      login({...userInfo,version:VUE_APP_VERSION}).then(response => {
        if (response.code !== 200) {
          reject(response.msg)
        }
        const data = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取登入信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject(response.msg)
        }
        state.user = data
        const { roles, user: { nickname, avatar }, introduction } = data
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', nickname)
        commit('SET_AVATAR', store.getters["url/urls"] + avatar)
        // commit('SET_AVATAR',"http://192.168.1.32:8030"+avatar)//avatar
        commit('SET_INTRODUCTION', introduction)
        var obj = {
          roleIds: state.roles
        }
        resolve(data)
        // menu(obj)
        //   .then((res) => {
        //     menus(asyncRoutes, res.data)
        //       .then((res) => {
        //         commit("SET_QUANXIAN", res)
        //       })
        //     })
        //   .catch((err) => {
        //     this.$message.error("网络错误");
        //   });
      }).catch(error => {
        reject(error)
      })
    })
  },


  // 登出
  logout({ commit, state, dispatch }) {

    return new Promise((resolve, reject) => {
      // console.log(asyncRoutes);
      // asyncRoutes.push(6)
      // console.log(asyncRoutes);
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)


    const { roles } = await dispatch('getInfo')

    resetRouter()
    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    // router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
